package com.light.component;

import javafx.application.Platform;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.lib.BatchingProgressMonitor;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomProgressMonitor extends BatchingProgressMonitor {

    private final ProgressBar progressBar;

    private final AtomicInteger progress;
    private final AtomicInteger total;

    private final SimpleDoubleProperty rate;

    private final Label label;

    public CustomProgressMonitor(ProgressBar progressBar, SimpleDoubleProperty rate) {
        this(progressBar, rate, null);
    }

    public CustomProgressMonitor(ProgressBar progressBar, SimpleDoubleProperty rate, Label label) {
        this.progressBar = progressBar;
        this.rate = rate;
        this.label = label;
        progress = new AtomicInteger(0);
        total = new AtomicInteger(100);
    }

    @Override
    protected void onUpdate(String taskName, int workCurr, Duration duration) {

    }

    @Override
    protected void onEndTask(String taskName, int workCurr, Duration duration) {

    }

    @Override
    protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone, Duration duration) {
        if (null != rate) {
            rate.set((double) (progress.get() + percentDone) / total.get());
        }
        if (label != null && StringUtils.isNoneBlank(taskName, String.valueOf(workCurr), String.valueOf(workTotal), String.valueOf(percentDone))) {
            Platform.runLater(() -> label.setText(taskName + ": " + percentDone + "% (" + workCurr + '/' + workTotal + ')'));
            progressBar.setProgress((double) (progress.get() + percentDone) / total.get());
        }
    }

    @Override
    protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone, Duration duration) {
        progress.addAndGet(percentDone);
        total.addAndGet(percentDone);
        if (label != null && StringUtils.isNoneBlank(taskName, String.valueOf(workCurr), String.valueOf(workTotal), String.valueOf(percentDone))) {
            Platform.runLater(() -> label.setText(taskName + ": " + percentDone + "% (" + workCurr + '/' + workTotal + ')'));
        }
    }
}
